<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<!-- 3、功能实现: 当发起多个请求时候，只能有一个在进行中的请求，当1个结束后下一个才继续。
function request(url) {
  return new Promise((resolve) => {
    console.log('fetch:', url);
    setTimeout(()=>{resolve(url)}, 1000);
  });
}

function fetchOnlyOne(url) {
  // 待实现    
}

fetchOnlyOne(1);
fetchOnlyOne(2);
fetchOnlyOne(3);
fetchOnlyOne(4);
期待结果输出结果: 1, 2, 3, 4 间隔1s输出。 -->
<body>
    <script>
        function request(url) {
            return new Promise((resolve) => {
                console.log('fetch:', url);
                setTimeout(()=>{resolve(url)}, 1000);
            });
        }

        var p1;

        function fetchOnlyOne(url) {
            if(typeof p1 === 'undefined'){
                p1 = new fetchReq()
            }
             p1.execute(url)
        }

        function fetchReq(){
            this.task = [];
            setTimeout(() => {
                this.next()
            }, 1000)
        }

        fetchReq.prototype.execute = function(url){
            let fn = ()=> {
                request(url).then(()=>{
                   this.next();
                })
            }
            this.task.push(fn)
            // return this;
        }

        fetchReq.prototype.next = function(){
            let fn = this.task.shift();
            fn && fn();
        }

        fetchOnlyOne(1);
        fetchOnlyOne(2);
        fetchOnlyOne(3);
        fetchOnlyOne(4);
          // 期待结果输出结果: 1, 2, 3, 4 间隔1s输出。
    </script>
</body>
</html>